import * as step from '@flow-step/step-toolkit'
import OSS from 'ali-oss'
import path from 'node:path'
import * as fs from 'fs'
import {UploadInputs} from './upload-inputs'
import * as util from "./util";

class CustomError extends Error {
    constructor(msg: string) {
        super(msg)
    }
}
export const customErrorInstance = new CustomError(
    'An error occurred when upload to OSS.'
)
export const authErrorInstance = new CustomError(
    'Access denied by authorizer policy for OSS.'
)

export async function put(artifact: UploadInputs) {
    artifact.repoId = ''
    if (artifact.fileId === undefined) {
        step.error("Failed to get params 'FILE_ID'")
        throw new Error("missing params 'FILE_ID'")
    }
    let endpoint = await util.getEndpoint()

    if (
        artifact.accessKeyId === undefined ||
        artifact.accessKeySecret === undefined
    ) {
        step.error('Access Denied for undefined as/sk')
        throw new Error('Access Denied for undefined as/sk')
    }
    const client = new OSS({
        endpoint: endpoint,
        accessKeyId: artifact.accessKeyId,
        accessKeySecret: artifact.accessKeySecret,
        bucket: artifact.bucketName,
        stsToken: artifact.token
    })

    try {
        artifact.fileParentId = path.dirname(artifact.fileId)
        const result = await client.put(
            artifact.fileId,
            artifact.artifactFullName
        )
        //输出写入params

        fs.unlinkSync(artifact.artifactFullName)
    } catch (e) {
        step.info("upload oss error "+e)

        fs.unlinkSync(artifact.artifactFullName)
        throw customErrorInstance
    }
}
